<template>
    <n-config-provider>
      <n-grid :x-gap="10" :y-gap="5" :cols="4">
        <n-grid-item>
          <n-button type="success" size="medium" @click="handelAdd">
            新增角色
          </n-button>
        </n-grid-item>
      </n-grid>
      <n-data-table
      :columns="columns"
      :data="rolelist"
      :pagination="pagination"
      :bordered="false"
      class="ptable"
    />
    <n-drawer v-model:show="drawerShow" :width="400" placement="right" >
        <n-drawer-content :title="editdata?'编辑角色信息':'新增角色'">
            <RoleForm :row-data="editdata" @role-list="handelRefresh"/>
        </n-drawer-content>
    </n-drawer>
    
    </n-config-provider>
  </template>
  
  <script setup>
  import { NButton, NImage, NTab, NTag, useDialog, useMessage } from 'naive-ui';
  import { ref,h } from 'vue';
  import { NConfigProvider } from 'naive-ui'
  import { useRouter} from 'vue-router';
  import RoleForm from './components/RoleForm.vue';
  import { roleGetApi } from '../../api/user';
  import { routes } from '../../router';
  import usePermission from '../../hooks/permissions';
  
  const {canUse} = usePermission(['root'])
  
  const rolelist = ref([]);
  roleGetApi().then(res=>{
    rolelist.value = res.data.data
  })

  // 表格配置
  function createColumns({
  del,
  edit
  }) {
    
    let columnArr= [
      {
        title: "角色ID",
        key: "_id",
        width:250
      },
      {
        title: "角色名称",
        key: "roleName",
        width:100,
      },
      {
        title: "代号",
        key: "role",
        width:100,
      },
      {
        title: "角色权限",
        key: "permission",
        render(row){
          let tagNodes = row.permission.map(key=>{
            return h(
              NTag,
              {type:'success',sizi:'small',style:'margin:2px'},
              { default: () => keyValues[key]}
            )
          })
          return tagNodes
        }
      },
      {
        title: "操作",
        key: "actions",
        render(row) {
          const btns=[
            {title:'编辑',type:'info',fuc:()=>{edit(row)}},
            {title:'删除',type:'Error',fuc:()=>{del(row)}},
          ]
          const btnsNode = btns.map((item)=>{
            return h(
              NButton,
              {type:item.type,onClick:item.fuc},
              { default: () => item.title}
            )
          })
          return btnsNode
        }
      }
    ];
    if(!canUse){
      columnArr.pop()
    }
    return columnArr;
  };
  const dialog = useDialog();
  const columns = createColumns({
    edit(row) {
      drawerShow.value = true
      editdata.value = row
    },
    async del(row) {
      console.log('删除');
      dialog.warning({
        title: "警告，删除后无法找回",
        content: `你确定要删除《${row.name}》吗？`,
        positiveText: "确定",
        negativeText: "取消",
        draggable: true,
        onPositiveClick: async() => {},
      });
    }
  });
  const pagination = ref({
    pageSize: 5,
  })
  // 抽屉控制
  const drawerShow = ref(false)
  const handelAdd = () => {
    drawerShow.value = true
    editdata.value = null
  }

  // 渲染角色权限对应的名称
  function routesToKeyValue(routesArr){
    let obj = {}
    // 递归遍历
    function loop(arr){
      arr.forEach(item => {
        obj[item.path] = item.label // 将path作为key，label作为value
        if(item.children){
          loop(item.children)
        }
      });
    }
    loop(routesArr)
    return obj
  }
  const keyValues = routesToKeyValue(routes[0].children)
  console.log('路由数据键值对',keyValues);
  // 编辑数据
  const editdata = ref(null)

  //子组件实时更新数据
  const handelRefresh = (formData)=>{
    console.log("接收到子组件数据",formData);
    drawerShow.value = false //关闭抽屉
    let len = rolelist.value.length
    for(let i = 0;i<len;i++){
      if(rolelist.value[i]._id == formData._id){
        rolelist.value[i] = formData //替换原数据
        return
      }
    }
    rolelist.value.push(formData) //新增数据
  }

  </script>
  
  <style lang="scss" scoped>
  //深度选择器
  .ptable :deep(.poster){
    height: 50px;
  }
  </style>